package com.trial.eyefollowupapp.screens

import androidx.compose.animation.*
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Logout
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.*
import androidx.navigation.NavHostController
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import com.trial.eyefollowupapp.RetrofitClient
import com.trial.eyefollowupapp.theme.AppAnimations
import com.trial.eyefollowupapp.theme.AppDimens
import androidx.compose.animation.core.tween
import androidx.compose.foundation.shape.RoundedCornerShape

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FollowUpScreen(
    navController: NavHostController,
    username: String,
    onRecordClick: (Int) -> Unit
) {
    val context = LocalContext.current
    val records = remember { mutableStateOf<List<FollowUpRecord>>(emptyList()) }
    var loading by remember { mutableStateOf(true) }
    var errorMsg by remember { mutableStateOf("") }
    var showList by remember { mutableStateOf(false) }

    // 加载数据
    LaunchedEffect(Unit) {
        try {
            val response = withContext(Dispatchers.IO) {
                RetrofitClient.instance.getRecords()
            }

            if (response.isSuccessful) {
                val recordsResponse = response.body()
                
                if (recordsResponse != null) {
                    val recordResponses = recordsResponse.records
                    
                    // 过滤记录
                    val filteredRecords = recordResponses.filter {
                        it.username == username
                    }
                    
                    records.value = filteredRecords.map {
                        FollowUpRecord(
                            id = it.id,
                            doctor = it.doctor_name,
                            date = it.date,
                            patient_name = it.username
                        )
                    }
                } else {
                    errorMsg = "响应体为空"
                }
            } else {
                errorMsg = "获取记录失败: ${response.code()}"
            }
        } catch (e: Exception) {
            errorMsg = "网络请求失败: ${e.message}"
            e.printStackTrace()
        } finally {
            loading = false
            showList = true
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("随访记录（$username）") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.Filled.ArrowBack, contentDescription = "返回")
                    }
                },
                actions = {
                    IconButton(onClick = {
                        // 回到登录页并清空返回栈
                        navController.navigate("login") {
                            popUpTo("home") { inclusive = true }
                        }
                    }) {
                        Icon(Icons.Filled.Logout, contentDescription = "退出登录")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary
                )
            )
        },
        contentWindowInsets = WindowInsets(0, 0, 0, 0)
    ) {
        if (loading) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator(
                    color = MaterialTheme.colorScheme.primary
                )
            }
        } else if (errorMsg.isNotEmpty()) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    errorMsg,
                    color = MaterialTheme.colorScheme.error,
                    style = MaterialTheme.typography.bodyLarge
                )
            }
        } else {
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(it)
                    .padding(AppDimens.spacingMedium),
                contentPadding = PaddingValues(AppDimens.spacingSmall)
            ) {
                if (records.value.isEmpty()) {
                    item {
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Text(
                                "暂无随访记录",
                                color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6f),
                                style = MaterialTheme.typography.bodyLarge
                            )
                        }
                    }
                } else {
                    items(records.value) {
                        AnimatedVisibility(
                            visible = showList,
                            enter = fadeIn(
                                animationSpec = tween(durationMillis = AppAnimations.durationMedium)
                            ) + scaleIn(
                                initialScale = 0.95f,
                                animationSpec = tween(durationMillis = AppAnimations.durationMedium)
                            ),
                            exit = fadeOut(
                                animationSpec = tween(durationMillis = AppAnimations.durationShort)
                            )
                        ) {
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = AppDimens.spacingSmall)
                                    .clickable { onRecordClick(it.id) },
                                elevation = CardDefaults.cardElevation(AppDimens.elevationMedium),
                                colors = CardDefaults.cardColors(
                                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                                ),
                                shape = RoundedCornerShape(AppDimens.cornerRadiusMedium)
                            ) {
                                Column(
                                    modifier = Modifier.padding(AppDimens.spacingMedium)
                                ) {
                                    Text(
                                        "📄 编号：${it.id}",
                                        style = MaterialTheme.typography.titleMedium
                                    )
                                    Text(
                                        "👨‍⚕️ 医生：${it.doctor}",
                                        style = MaterialTheme.typography.bodyLarge
                                    )
                                    Text(
                                        "📅 日期：${it.date}",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

data class FollowUpRecord(
    val id: Int,
    val doctor: String,
    val date: String,
    val patient_name: String? = null,
    val left_eye_image: String? = null,
    val right_eye_image: String? = null
)
